﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using GroundWater.Data;
using GroundWater.BusinessActions;
using MonitoringTable = GroundWater.Data.MonitoringDataSet.MonitoringDataTable;
using MonitoringRow = GroundWater.Data.MonitoringDataSet.MonitoringRow;

using WellTable = GroundWater.Data.InfoDataSet.WellsDataTable;
using WellRow = GroundWater.Data.InfoDataSet.WellsRow;

using SectionPlaneTable = GroundWater.Data.InfoDataSet.SectionPlaneDataTable;
using SectionPlaneRow = GroundWater.Data.InfoDataSet.SectionPlaneRow;



namespace GroundWater.analysis
{
    public partial class SectionPlaneWaterlevel : PageBase
    {
        
        private bool registered = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "剖面水位及埋深统计");
            if (!this.IsPostBack)
            {
                txtStartDate.Text = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");
                txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

            }

            BoundData();

            //sm.RegisterAsyncPostBackControl(this.btnAnalysis);
            //sm.RegisterAsyncPostBackControl(this.drpSectionPlane);
        }

        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }
        }


        protected void btnAnalysis_Click(object sender, EventArgs e)
        {
            //RegisterDataItem();
            BoundData();
        }

        protected void drpSectionPlane_SelectedIndexChanged(object sender, EventArgs e)
        {
            RegisterDataItem();
        }

        protected void drpSectionPlane_DataBound(object sender, EventArgs e)
        {
            
        }

        //private string GetWaterlevel()
        //{
        //    if (txtStartDate.Text.Length < 8 || txtEndDate.Text.Length < 8)
        //        return "";

        //    decimal altitude = 0m;
        //    decimal waterlevel = 0m;
        //    WellTable wells = Well.GetAll(false, true);
        //    var rows = wells.AsEnumerable();

        //    DataTable dtSectionPlane = Monitoring.FetchWaterLeveAllBySectionPlane(txtStartDate.Text, txtEndDate.Text);
        //    gvMonitoring.DataSource = dtSectionPlane;
        //    gvMonitoring.DataBind();

        //    updPanel.Update();

        //    if (drpSectionPlane.SelectedValue == "-1")
        //    {
        //        altitude = wells.Average(r => r.Altitude);

        //        var planes = dtSectionPlane.AsEnumerable();
        //        waterlevel = Math.Round(planes.Average(r => Convert.ToDecimal(r["Waterlevel"])), 2);
        //    }
        //    else
        //    {
                
        //        DataRow plane = dtSectionPlane.AsEnumerable().SingleOrDefault(r => r["SectionPlane"].ToString() == drpSectionPlane.SelectedItem.Text);

                
        //        if (plane != null)
        //        {
        //            waterlevel = (decimal)plane[1];//plane["Waterlevel"];
        //        }
        //        var sectionWells = rows.Where(r => r.SectionPlane == drpSectionPlane.SelectedItem.Text);
        //        if (sectionWells == null || sectionWells.Count() == 0)
        //            return "";
        //        altitude = sectionWells.Average(r => r.Altitude);
        //    }

            
        //    if (altitude <= waterlevel)
        //    {
        //        return waterlevel.ToString();
        //    }
        //    decimal tmp = altitude - waterlevel;

        //    string s = waterlevel.ToString() + "|" + tmp.ToString();

        //    return s;

        //}

        private void RegisterDataItem()
        {
            //string s = GetWaterlevel();
            //if (s.Length > 0 && !registered)
            //{
            //    sm.RegisterDataItem(this.btnAnalysis, s);
            //    registered = !registered;
            //}
        }

        private void BoundData()
        {
            // 得到各个剖面的平均水位
            DataTable dtSectionPlane = Monitoring.FetchWaterLeveAllBySectionPlane(txtStartDate.Text, txtEndDate.Text);
            // 得到所有水井
            WellTable wells = Well.GetAll(false, true);
            // 得到所有剖面
            SectionPlaneTable allPlanes = GroundWater.BusinessActions.SectionPlane.GetAll(false, true);

            var ps = allPlanes.AsEnumerable();
            var wellRows = wells.AsEnumerable();
            var planes = dtSectionPlane.AsEnumerable();

            // 整个流域上所有水井的平均地面高程
            decimal altitude = wells.Average(r => r.Altitude);

            // 得到整个流域的平均水位
            decimal waterlevel = 0;
            if (planes.Count() > 0)
                waterlevel = Math.Round(planes.Average(r => Convert.ToDecimal(r["Waterlevel"])), 2);

            var wellAltitude = from w in wellRows
                               group w by w.SectionPlane into g
                               select new { SectionPlane = g.Key, Altitude = g.Average(w => w.Altitude) };
            var q = from w in wellAltitude
                    join p in planes on w.SectionPlane equals p["SectionPlane"]
                    select new { Plane = w.SectionPlane, WaterLevel = Convert.ToDecimal( p["Waterlevel"]), Altitude = w.Altitude };

            var pw = q.ToList();

            var ret = from i in pw
                    join s in ps on i.Plane equals s.Name
                    orderby s.Code
                      select new { Plane = i.Plane, WaterLevel = i.WaterLevel, Altitude = i.Altitude - i.WaterLevel };

            var rr = ret.ToList();

            rr.Add(new { Plane = "整个流域", WaterLevel = waterlevel, Altitude = altitude - waterlevel });



            gvMonitoring.DataSource = rr;
            gvMonitoring.DataBind();
        }
    }
}
